<template>
	<div class="detail-wrapper" v-if="showDetail">
    <!-- 定制 鼎兴餐饮 新详情页 -->
    <template v-if="!is_dxcy_gift_bag_dz">
    <div class="top-wrap">
      <!-- 后台：商品评价--关闭后商品详情页将不显示评价和顶部主页按钮 -->
      <top-shade :topInfo="topInfo" :detailAll="detailAll" v-if="showDetailAjax"/>

      <top-banner :itemDetail="itemDetail" v-if="showDetailAjax"></top-banner>
    </div>

    <div class="mid-wrap">
      <middle-info :detailAll="detailAll" :diyData="diyData" :off_shelf_status="off_shelf_status"></middle-info>
    </div>

    <!-- 群接龙活动商品详情底部弹层 -->
    <solitaire-btn ref="SolitaireBtn" v-if="$route.query.activity_type == 'solitaire'"></solitaire-btn>

    <div class="bottom-fixed" v-else>
      <!-- is_view_the_details: 商品分组限制权限时可以进入详情但是没有操作按钮 -->
      <fixed-button :detailAll="detailAll" :off_shelf_status="off_shelf_status" v-if="showDetailAjax && !is_view_the_details" />
    </div>
    </template>
    <template v-else>
      <div class="top-wrap">
        <top-banner :itemDetail="itemDetail" v-if="showDetailAjax"></top-banner>
      </div>
      <dz-middle :detailAll="detailAll" />
    </template>
  </div>
</template>

<script>
/**
   * @Author: yqe@360shop.cn
   * @Date: 2019-12-04 19:43:18
 * @Last Modified by: zhangmeng
 * @Last Modified time: 2020-12-17 14:13:09
   */
import Vue from 'vue'
import topShade from './topShade'
import topBanner from './topBanner'
import middleInfo from './middleInfo'
import dzMiddle from './middleInfo/dzWeb'
import fixedButton from './fixedButton'
import solitaireBtn from '@/views/activity/groupSolitaire/components/solitaireBtn'
import Store from '@/utils/store'
import { getDetail, getDetailAjax, itemDetailHtmlCache, GroupShoppingDetail, newItemDetailDiyHtml } from '@/api/item/item'
import small from '@/smallapp/small'
import { openPage, mpShare } from '@/utils/utils'

export default Vue.extend({
  name: 'index',
  components: {
    topBanner,
    middleInfo,
    topShade,
    fixedButton,
    solitaireBtn,
    dzMiddle
  },
  data() {
    return {
      showShade: false,
      shareInfo: {},
      sid: '',
      showDetailAjax: false,
      showDetail: false,
      detailAjaxParams: {
        item_id: '',
        // 供应商id（可不传 替换成supplier）
        supplier: '',
        aid: '',
        // 搭配套餐id
        is_no_dhs: '',
        // 是否不是订货商传0，1
        p: '',
        // 页码
        bid: '',
        // 是否原价购买
        item_preview: '',
        // 商品预览传0，1
        store_id_cost: '',
        // 内购门店id
        ng_store_id: ''
      },
      detailParams: {
        page: '',
        id: '',
        no_group: '',
        item_preview: '',
        is_preview: '',
        livingfrom: '',
        source: '',
        live_id: '',
        supplier: '',
        store_id_cost: '',
        aid: '',
        // 内购门店id
        ng_store_id: ''
      },
      topInfo: {
        user_need_open_store_gift: 0,
        showTj: false,
        has_material: 0,
        is_comment: 0
      },
      is_view_the_details: 0,
      diyData: {},
      detailAll: {},
      off_shelf_status: 0, // 0是未下架 1是已下架
      itemDetail: {},
      diyHtml: '',
      description: '',
      bottomHtml: '',
      is_item_detail_blank: '',
      isPreview: '',
      modulePadding: '',
      // coupon_listscount: [],
      detail_goods_recommendation: 0,
      goods_recommend_names: '',
      opzm_dz: 0,
      is_detail_code: '0',
      item_qrcode_is_pull_down: '0',
      is_online_course: 0, // 是否是在线微课
      provu: 0, // 是否显示试看
      has_material: 0,
      course_brought_before: 0, // 是否购买过在线微课,
      // item_coupon_value: '', // 券后价格
      smallQuery: {},
      is_dxcy_gift_bag_dz: 0, // 定制 鼎兴餐饮 定制字段
    }
  },
  methods: {
    init(options) {
      // console.log('init options', options, this.$route)
      this.$loadingWrap.show()
      // detail接口参数
      this.detailParams.page = options.page
      this.detailParams.id = options.detailId || options.item_id
      this.detailParams.no_group = options.no_group || '1'
      this.detailParams.item_preview = options.item_preview
      this.detailParams.is_preview = options.is_preview
      this.detailParams.livingfrom = options.livingfrom
      this.detailParams.source = options.source
      this.detailParams.live_id = options.live_id
      this.detailParams.supplier = options.supplier
      this.detailParams.store_id_cost = options.store_id_cost
      this.detailParams.aid = options.aid
      this.detailParams.ng_store_id = options.storeId
      // detailAjax接口参数
      this.detailAjaxParams.item_id = options.detailId || options.item_id
      this.detailAjaxParams.supplier = options.supplier
      this.detailAjaxParams.aid = options.aid
      this.detailAjaxParams.is_no_dhs = options.is_no_dhs
      this.detailAjaxParams.p = options.p
      this.detailAjaxParams.bid = options.bid
      this.detailAjaxParams.item_preview = options.item_preview
      this.detailAjaxParams.store_id_cost = options.store_id_cost
      this.detailAjaxParams.ng_store_id = options.storeId

      const item_id = options.detailId || options.item_id
      const group_shopping_id = options.groupId
      const tuanId = options.tuanId
      const tuanOrderId = options.tuanOrderId
      if (this.$route.name == 'item-group') {
        // 拼团商品详情
        const params = {
          item_id,
          group_shopping_id,
          tuanId,
          tuanOrderId,
          supplier: options.supplier
        }
        if (options.is_scan == 1) {
          params.is_scan = 1
        }
        GroupShoppingDetail(params).then((res) => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            const resData = res.data
            this.detailAll = resData
            this.is_view_the_details = resData.is_view_the_details
            this.is_online_course = resData.is_online_course
            this.provu = resData.provu
            this.topInfo.has_material = this.has_material = resData.has_material || 0
            this.course_brought_before = resData.course_brought_before
            this.itemDetail = resData.item_detail
            this.topInfo.user_need_open_store_gift = resData.user_need_open_store_gift
            this.topInfo.showTj = false
            this.topInfo.is_detail_code = resData.is_detail_code
            this.topInfo.item_qrcode_is_pull_down = resData.item_qrcode_is_pull_down
            // 商品二维码
            // this.topInfo.qrcode = this.detailAll.qrcode = resData.item_qrcode ? resData.item_qrcode : '/Public/itemDetailQrcode?item_id=' + resData.item_detail.item_id + '&sid=' + this.sid
            this.topInfo.supplier_index_link = this.detailAll.supplier_index_link = resData.supplier_index_link
            this.topInfo.index_link = this.detailAll.index_link = resData.index_link
            this.topInfo.is_close_item_shop = res.data.is_close_item_shop
            this.topInfo.is_comment = resData.is_comment
            this.detailAll.isGroup = true
            this.detailAll.activity = '99'
            Store.save('viewLog', {
              item_id: res.data.item_detail.item_id,
              title: res.data.item_detail.title,
              num: res.data.item_detail.num,
              real_sales: res.data.item_detail.real_sales,
              price: res.data.item_detail.price,
              link: res.data.item_detail.link,
              img_url: res.data.item_detail.img_path[0]
            })

            // 缓存商品信息
            const kfCard = {
              customCardId: this.itemDetail.item_id,
              customCardLink: window.location.href,
              img_url: this.itemDetail.img_path[0],
              title: this.itemDetail.title,
              link: `/goods/pages/itemGroup/index?groupId=${params.group_shopping_id}&item_id=${params.item_id}&type=open&targeturl=${encodeURIComponent('/item-group')}&groupId=${params.group_shopping_id}&item_id=${params.item_id}`
            }
            small.wxCache('kfCard', kfCard)
            this.$Bus.$emit('handleChange', kfCard)
            // 十人团 定制 字段 start
            if (resData.info.aggregation_type && resData.info.aggregation_type == 6) {
              this.detailAll.is_ten_group = true
            } else {
              this.detailAll.is_ten_group = false
            }
            // 十人团 定制 字段 end
            // TODO 小程序分享
            this.shareInfo = {
              title: res.data.jsapi_title,
              imgUrl: res.data.jsapi_img,
              shareParam: res.data.jsapi_url ? res.data.jsapi_url.split('?')[1] : ''
            }
            mpShare(true, false, '/goods/pages/itemGroup/index', this.shareInfo)
            

            // 如果有视频，轮播图多一张主图
            if (resData.item_detail.video_url) {
              resData.item_detail.img_path.unshift(resData.item_detail.img_path[0])
              this.itemDetail.img_path = resData.item_detail.img_path
            }
            this.showDetailAjax = true
            this.showDetail = true
          } else {
            this.$Error(res.msg)
          }
        })
      } else {
        // 判断是不是拼团
        if (this.detailParams.no_group == 1) {
          itemDetailHtmlCache({ uri: window.location.href }).then((res) => {
            if (res.status == 1) {
              if (typeof res.data.link === 'string' && res.data.link.length > 0) {
                openPage(res.data.link)
              }
            } else {
              this.$Error(res.msg)
            }
          })
        }
        if (options.is_scan == 1) {
          this.detailParams.is_scan = 1
        }
        getDetail(this.detailParams).then((res) => {
          if (res.status == 1) {
            this.is_view_the_details = res.data.is_view_the_details
            this.$store.dispatch('getItemSupplierQQ', res.data.supplier_qq)
            this.showDetail = true
            this.is_online_course = res.data.is_online_course
            this.provu = res.data.provu
            this.topInfo.has_material = this.has_material = res.data.has_material || 0
            this.course_brought_before = res.data.course_brought_before
            this.shareInfo = {
              title: res.data.jsapi_title,
              imgUrl: res.data.jsapi_img,
              shareParam: res.data.jsapi_url ? res.data.jsapi_url.split('?')[1] : ''
            }
            this.is_item_detail_blank = res.data.is_item_detail_blank
            this.isPreview = res.data.isPreview
            this.modulePadding = res.data.modulePadding
            this.detail_goods_recommendation = res.data.detail_goods_recommendation || 0
            this.goods_recommend_names = res.data.goods_recommend_names
            this.opzm_dz = res.data.opzm_dz
            this.topInfo.is_detail_code = this.is_detail_code = res.data.is_detail_code
            this.topInfo.item_qrcode_is_pull_down = this.item_qrcode_is_pull_down = res.data.item_qrcode_is_pull_down
            this.topInfo.index_link = res.data.index_link
            this.topInfo.is_close_item_shop = res.data.is_close_item_shop
            this.off_shelf_status = res.data.item_detail.off_shelf_status
            this.detailAll.is_online_course = this.is_online_course
            this.detailAll.provu = this.provu
            this.detailAll.course_brought_before = this.course_brought_before
            if (res.data.page_title) {
              wx.setNavigationBarTitle({
                title: res.data.page_title
              })
            }
            // TODO 增加判断
            if (res.data.item_detail && res.data.item_detail.item_id) {
              Store.save('viewLog', {
                item_id: res.data.item_detail.item_id,
                title: res.data.item_detail.title,
                num: res.data.item_detail.num,
                real_sales: res.data.item_detail.real_sales,
                price: res.data.item_detail.price,
                link: res.data.item_detail.link,
                img_url: res.data.item_detail.img_path[0]
              })
            }
            const routeName = this.$route.name
            const viewLog = Store.fetch('viewLog')
            // 商品浏览记录
            let recent_goods = []
            if (window.localStorage) {
              // 商品和拼团商品详情页 存入浏览记录
              if (routeName == 'item-detail' || routeName == 'item-group') {
                if (localStorage.getItem('recent_goods')) {
                  recent_goods = JSON.parse(localStorage.getItem('recent_goods'))
                  // 当前商品id
                  const curId = viewLog.item_id
                  for (let i = 0; i < recent_goods.length; i++) {
                    if (!recent_goods[i]) {
                      // 清空
                      localStorage.removeItem('recent_goods')
                      return false
                    }
                    // 如果已经有记录，删除原来那一条
                    if (curId == recent_goods[i].item_id) {
                      recent_goods.splice(i, 1)
                      break
                    }
                  }
                  // 向数组的开头添加
                  if (viewLog) {
                    recent_goods.unshift(viewLog)
                  }
                  if (recent_goods.length > 20) {
                    // 如果长度大于20.截取前20项
                    recent_goods = recent_goods.slice(0, 20)
                  }
                  localStorage.setItem('recent_goods', JSON.stringify(recent_goods))
                } else {
                  if (viewLog) {
                    recent_goods.unshift(viewLog)
                  }
                  localStorage.setItem('recent_goods', JSON.stringify(recent_goods))
                }
              } else if (localStorage.getItem('recent_goods')) {
                recent_goods = JSON.parse(localStorage.getItem('recent_goods'))
              }
            } else {
              // console.log('浏览器不支持localstorage!')
            }
            
            // TODO 小程序分享
            mpShare(true, true, '/goods/pages/itemDetail/index', this.shareInfo)

            getDetailAjax(this.detailAjaxParams).then((res) => {
              this.$loadingWrap.close()
              if (res.status == 1) {
                const resData = res.data
                this.detailAll = resData
                this.detailAll.is_online_course = this.is_online_course
                this.detailAll.provu = this.provu
                this.detailAll.has_material = this.has_material
                this.detailAll.course_brought_before = this.course_brought_before
                // 处方药新增字段  tszd_info
                this.detailAll.tszd_info = res.data.tszd_info || null
                this.detailAll.is_item_detail_blank = this.is_item_detail_blank
                this.detailAll.detail_goods_recommendation = this.detail_goods_recommendation
                this.detailAll.goods_recommend_names = this.goods_recommend_names
                this.detailAll.opzm_dz = this.opzm_dz
                this.detailAll.is_detail_code = this.is_detail_code
                this.detailAll.item_qrcode_is_pull_down = this.item_qrcode_is_pull_down
                this.detailAll.index_link = this.topInfo.index_link
                this.detailAll.is_close_item_shop = this.topInfo.is_close_item_shop
                this.topInfo.is_comment = resData.is_comment

                this.itemDetail = resData.item_detail
                this.topInfo.supplier_index_link = resData.supplier_index_link
                this.topInfo.user_need_open_store_gift = resData.user_need_open_store_gift
                // 定制 鼎兴餐饮 是否是套餐商品
                if (resData.is_dxcy_gift_bag_dz && resData.dxcy_gift_bag_item_list && resData.dxcy_gift_bag_item_list.dxcy_gift_open == 1) {
                  this.is_dxcy_gift_bag_dz = 1
                } else {
                  this.is_dxcy_gift_bag_dz = 0
                }
                if (this.detailAll.supplier_info && this.detailAll.supplier_info.id > 0) {
                  this.$Bus.$emit('reloadLayout', { supplier: this.detailAll.supplier_info.id })
                }
                if (this.detail_goods_recommendation == 1) {
                  this.topInfo.showTj = true
                } else {
                  this.topInfo.showTj = false
                }
                // 缓存商品信息
                const kfCard = {
                  customCardId: this.itemDetail.item_id,
                  customCardLink: window.location.href,
                  img_url: this.itemDetail.img_path[0],
                  title: this.itemDetail.title,
                  link: `/goods/pages/itemDetail/index?detailId=${this.detailAjaxParams.item_id}&type=open&targeturl=${encodeURIComponent('/item-detail')}&detailId=${this.detailAjaxParams.item_id}`
                }
                small.wxCache('kfCard', kfCard)
                this.$Bus.$emit('handleChange', kfCard)
                // 定制 野火教育 start
                this.detailAll.wild_fire_education = res.data.wild_fire_education
                this.detailAll.wild_fire_contract_tea_pic = res.data.wild_fire_contract_tea_pic
                // 定制 野火教育 ent
                // 如果有视频，轮播图多一张主图
                if (resData.item_detail.video_url && resData.item_detail.video_type === 1) {
                  resData.item_detail.img_path.unshift(resData.item_detail.img_path[0])
                  this.itemDetail.img_path = resData.item_detail.img_path
                }
                this.showDetailAjax = true
              } else {
                this.$Error(res.msg)
              }
            })
          } else {
            this.$loadingWrap.close()
            // TODO 返回链接则进行跳转
            if (res.data && res.data.redirect_url) {
              openPage(res.data.redirect_url, 1)
            } else {
              res.msg ? this.$Error(res.msg) : ''
            }
          }
        })
      }
    }
  },
  created() {
    if (this.$route.query.sid) {
      this.sid = this.$route.query.sid
    } else {
      this.sid = Store.fetchLocal('sid') ? Store.fetchLocal('sid') : undefined
    }
  },
  mounted() {
      window.addEventListener('wxload', (query) => {
        // console.log(query, '监听页面参数')
        if (query.scene) { // 当是小程序码扫码进入的时候
          if (query.room_id) {
            // 处理直播间商品进入小程序数据整理，注册时需要，请谨慎改动
            const zbparams = {}
            zbparams.room_id = query.room_id
            zbparams.share_openid = query.share_openid
            zbparams.openid = query.openid
            zbparams.custom_params = query.custom_params
            small.wxCache('ZB_PARAMS', zbparams)
          }
          // 存储微视tx_trace_key,15天
          if(query.tx_trace_key){
            small.wxCache('tx_trace_key', query.tx_trace_key, 15 * 24 * 60 * 60)
          }
        } else {
          // TODO 处理分享参数
          this.smallQuery = Object.assign(this.$route.query, query)
          // console.log(this.smallQuery, 'this.smallQuery11')
          // 存储微视tx_trace_key，15天
          if(this.smallQuery.tx_trace_key){
            small.wxCache('tx_trace_key', this.smallQuery.tx_trace_key, 15 * 24 * 60 * 60)
          }
          small.HandleShareParams()
          this.init(this.smallQuery)
        }
      })
      window.addEventListener('wxshow', () => {
        // console.log(this.smallQuery, 'wxshow')
        this.init(this.smallQuery)
      });
      window.$$subscribe('loginReload', (reload) => {
        // console.log(this.smallQuery, 'smallQuery')
        if (reload) {
          this.init(this.smallQuery)
        }
      })
      window.$$subscribe('refreshMiaosha', () => {
        this.init()
      })
  },
  beforeDestroy() {
    this.$off()
    window.$$unsubscribe('loginReload')
  }
})
</script>

<style lang="scss">
  .detail-wrapper{
    padding-bottom: 40px;
    .shade-wrap-icon{
      position: absolute;
      top:0;
      left:0;
      z-index:3;
      width:100%;
      padding: 20px 0;
      &-item{
        width: 60px;
        height: 60px;
        background: rgba(0,0,0, 0.6);
        border-radius: 50%;
        display: inline-block;
        margin-right: 20px;
        color: #666;
        &:first-child{
          margin-left: 20px;
        }
        .icon-top{
          color: #fff;
          line-height: 60px;
          text-align: center;
          font-size: 36px;
          &.home{
            font-size: 40px;
          }
        }
      }
    }
  }
</style>
